package com.yinhe.music.yhmusic.search;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.hwangjr.rxbus.RxBus;
import com.hwangjr.rxbus.annotation.Subscribe;
import com.hwangjr.rxbus.annotation.Tag;
import com.hwangjr.rxbus.thread.EventThread;
import com.yinhe.music.event.RxBusEventType;
import com.yinhe.music.event.RxbusNullObject;
import com.yinhe.music.yhmusic.R;
import com.yinhe.music.yhmusic.base.BaseModel;
import com.yinhe.music.yhmusic.base.BasePresenter;
import com.yinhe.music.yhmusic.base.BaseServiceActivity;
import com.yinhe.music.yhmusic.search.adapter.SearchAdapter;
import com.yinhe.music.yhmusic.utils.Preferences;
import com.yinhe.music.yhmusic.utils.ToastUtils;
import com.yinhe.music.yhmusic.widget.WrapContentLinearLayoutManager;

import java.util.List;

import butterknife.BindView;

/**
 * @author 何晓华
 */
public class SearchActivity extends BaseServiceActivity implements View.OnClickListener, TextWatcher,
        BaseQuickAdapter.OnItemClickListener, SearchContract.ISearchView {
    @BindView(R.id.searchView)
    EditText mSearchView;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.brief_search)
    FrameLayout briefSearch;
    @BindView(R.id.search_line)
    View searchLine;
    @BindView(R.id.search_image)
    ImageView searchImage;

    SearchPresenter mPresenter;

    private TextView briefTips;
    private SearchAdapter searchAdapter;
    private SearchResultFragment resultFragment;

    @Override
    public void initView() {
        RxBus.get().register(this);
        setToolbar("搜索");
        showQuickControl(true);
        initRecyclerView();
        initSearch();
        SearchFragment searchFragment = new SearchFragment();
        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction tx = fm.beginTransaction();
        tx.add(R.id.FrameLayout, searchFragment);
        tx.commit();
    }

    @Override
    protected void onDestroy() {
        RxBus.get().unregister(this);
        super.onDestroy();
    }

    @Override
    public int getLayoutResId() {
        return R.layout.activity_search;
    }

    @Override
    public BasePresenter getPresenter() {
        return mPresenter;
    }

    @Override
    public void initPresenter() {
        mPresenter = new SearchPresenter();
        mPresenter.attachModelView(new BaseModel(), this);
    }

    private void initSearch() {
        mSearchView.setFocusable(true);
        mSearchView.setFocusableInTouchMode(true);
        mSearchView.requestFocus();
        InputMethodManager inputManager = (InputMethodManager) mSearchView.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        inputManager.showSoftInput(mSearchView, 0);

        mSearchView.setImeOptions(EditorInfo.IME_ACTION_SEARCH);
        mSearchView.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_UP) {
                    ((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE))
                            .hideSoftInputFromWindow(SearchActivity.this.getCurrentFocus().getWindowToken(),
                                    InputMethodManager.HIDE_NOT_ALWAYS);
                    search(mSearchView.getText().toString().trim());
                }
                return false;
            }
        });

        showSoftKeyboard(mSearchView);
        mSearchView.addTextChangedListener(this);
        searchImage.setOnClickListener(this);
    }

    private void search(String searchContext) {
        if (resultFragment != null) {
            getSupportFragmentManager().beginTransaction().show(resultFragment).commit();
        }

        briefSearch.setVisibility(View.GONE);
        searchLine.setVisibility(View.VISIBLE);

        if (TextUtils.isEmpty(searchContext)) {
            ToastUtils.show("请输入搜索内容");
        } else {

            List<String> list = Preferences.getSearchHistory();
            if (!list.contains(searchContext)) {
                Preferences.saveSearchHistory(searchContext);
            }
            if (resultFragment == null) {
                resultFragment = new SearchResultFragment();
                Bundle bundle = new Bundle();
                bundle.putString("key", searchContext);
                resultFragment.setArguments(bundle);
                FragmentManager fm = getSupportFragmentManager();
                FragmentTransaction tx = fm.beginTransaction();
                tx.replace(R.id.FrameLayout, resultFragment);
                tx.commitAllowingStateLoss();
            } else {
                resultFragment.setData(searchContext);
            }
        }
    }

    private void initRecyclerView() {
        searchAdapter = new SearchAdapter(R.layout.brief_search_list_item);
        searchAdapter.addHeaderView(getHeadView(getLayoutInflater()));
        recyclerView.setLayoutManager(new WrapContentLinearLayoutManager(this));
        recyclerView.setHasFixedSize(true);
        recyclerView.setAdapter(searchAdapter);
        searchAdapter.setOnItemClickListener(this);
    }

    private View getHeadView(LayoutInflater inflater) {
        View view = inflater.inflate(R.layout.brief_search_header, (ViewGroup) recyclerView.getParent(), false);
        briefTips = view.findViewById(R.id.search_tips);
        briefTips.setOnClickListener(this);
        return view;
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        hideSoftKeyboard();
        if (id == R.id.search_tips || id == R.id.search_image) {
            search(mSearchView.getText().toString().trim());
        }
    }


    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        if (s.length() > 0) {
            briefSearch.setVisibility(View.VISIBLE);
            searchLine.setVisibility(View.GONE);
            if (resultFragment != null) {
                getSupportFragmentManager().beginTransaction().hide(resultFragment).commit();
            }
            String content = s.toString();
            briefTips.setText(String.format("搜索“%s”", content));
            mPresenter.getSearchTips(content);
        } else {
            if (resultFragment != null) {
                getSupportFragmentManager().beginTransaction().show(resultFragment).commit();
            }
            briefSearch.setVisibility(View.GONE);
            searchLine.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void afterTextChanged(Editable s) {

    }

    @Override
    public void setSearchTipsUI(List<String> tipsList) {
        searchAdapter.setNewData(tipsList);
    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        String briefText = (String) adapter.getData().get(position);
        hideSoftKeyboard();
        mSearchView.setText(briefText);
        mSearchView.setFocusable(true);
        mSearchView.setSelection(briefText.length());
        search(briefText);
    }

    @Subscribe(
            thread = EventThread.MAIN_THREAD,
            tags = @Tag(RxBusEventType.Search.SEARCH_FROM_HISTORY)

    )
    public void onRxbusSearch(String content) {
        mSearchView.setText(content);
        mSearchView.setFocusable(true);
        mSearchView.setSelection(content.length());
        search(content);
    }

    @Override
    public void onBackPressed() {
        //crash fix:Can not perform this action after onSaveInstanceState
        if (!isFinishing()) {
            super.onBackPressed();
        }
    }

    @Subscribe(
            thread = EventThread.MAIN_THREAD,
            tags = @Tag(RxBusEventType.Search.HIDE_SOFT_KEYBOARD)

    )
    public void onRxbusScroll(RxbusNullObject rxbusNullObject) {
        hideSoftKeyboard();
    }
}
